import json
from django.db.models import Q
from django.http import JsonResponse
from haystack.views import SearchView
from rest_framework.generics import ListAPIView, GenericAPIView, RetrieveAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from headline.models import Article, Comment
from headline.serializers.article import ArticleSerializer
from scf_project.utils.pagenum import PageNum
from users.models import User


# 文章列表
# class ArticleListlView(APIView):
#     """文章列表"""
#
#     def get(self, request, id):
#         # 接收参数
#         page = request.GET.get('page')
#         # 判断参数
#         if id == '-1':
#             articles_obj = Article.objects.all()
#         else:
#             articles_obj = Article.objects.filter(channel_id=id)
#         results = []
#         for article in articles_obj:
#             # 遍历获得每个文章对象
#             user_obj = User.objects.get(id=article.user_id)
#             # 根据文章id获得作者
#             user_articles = Article.objects.filter(user_id=user_obj.id)
#             # 根据作者id获得作者发表的文章
#             articles = []
#             for i in user_articles:
#                 # 获取每篇文章的id和title
#                 articles.append({'id': i.id,
#                                  'title': i.title})
#             user_fans = user_obj.fans.all()
#             # 根据用户id获取粉丝
#             fans = []
#             for j in user_fans:
#                 fans.append(j.id)
#             users = {'id': user_obj.id,
#                      'username': user_obj.username,
#                      'avatar': user_obj.avatar,
#                      'articles': articles,
#                      'fans': fans}
#             # 获取收藏该文章的用户
#             article = Article.objects.get(id=article.id)
#             # collected_users = user_obj.collected_articles.all()
#             # collected_users = headline.user_set.all()
#             collecter = article.collected_users.all()
#             collected_users = []
#             for p in collecter:
#                 collected_users.append(p.id)
#
#             # print(collected_users)
#             # 判断文章是否被收藏
#             if user_obj in collecter:
#                 collected = True
#             else:
#                 collected = False
#             results.append({'id': article.id,
#                             'title': article.title,
#                             'content': article.content,
#                             'createtime': article.createtime,
#                             'user': users,
#                             'collected_users': collected_users,
#                             'collected': collected,
#                             'image': article.image
#                             })
#         # page = request.GET.get('page')
#         # pg = PageNum()
#
#         return Response({'count': len(results),
#                          'next': f'http://52.83.143.113:8880/article/{id}/channel/?page={page}',
#                          'results':results})
# 文章列表
class ArticleListView(ListAPIView):
    serializer_class = ArticleSerializer
    pagination_class = PageNum

    def get_queryset(self):
        id = self.kwargs.get('id')
        if id == '-1':
            return Article.objects.all().order_by('id')
        else:
            return Article.objects.filter(channel_id=id)

    # def list(self, request, *args, **kwargs):
    #     queryset = self.filter_queryset(self.get_queryset())
    #
    #     page = self.paginate_queryset(queryset)
    #
    #     if page is not None:
    #         serializer = self.get_serializer(page, many=True)


# 收藏或取消收藏
class ArticleCollectView(APIView):
    """收藏或取消收藏"""

    def put(self, request, id):
        # 获取用户对象
        user = request.user
        # 获取文章对象
        article = Article.objects.get(id=id)
        # 获取文章的收藏者
        users = article.collected_users.all()
        # 判断文章是否被收藏
        if user in users:
            # 被收藏，取消收藏
            article.collected_users.remove(user)
            article.save()
            return Response({'message': '取消收藏成功',
                             'success': 'true'})
        else:
            # 没有收藏，添加收藏
            article.collected_users.add(user)
            article.save()
            return Response({'message': '收藏成功',
                             'success': 'true'})


# 文章详情
# class ArticleDetailView(APIView):
#     def get(self, request, id):
#         article = Article.objects.get(id=id)
#         # 获取文章对象
#         user = User.objects.get(id=article.user_id)
#         # 获取作者
#         user_articles = Article.objects.filter(user_id=user.id)
#         # 获取作者的所有文章
#         articles = []
#         for user_article in user_articles:
#             articles.append({'id': user_article.id,
#                              'title': user_article.title})
#         user_fans = user.fans.all()
#         # 获取用户粉丝
#         fans = []
#         for fan in user_fans:
#             fans.append(fan.id)
#         user_data = {'id': user.id,
#                      'username': user.username,
#                      'avatar': user.avatar,
#                      'articles': articles,
#                      'fans': fans}
#         comments = Comment.objects.filter(article_id=article.id)
#         # 获取评论对象
#         comment_data = []
#         for comment in comments:
#             comment_user = User.objects.get(id=comment.user_id)
#             # 获取评论的用户
#             comment_user_articles = Article.objects.filter(user_id=comment_user.id)
#             # 获取评论用户的文章
#             comment_articles = []
#             for i in comment_user_articles:
#                 comment_articles.append({'id': i.id,
#                                          'title': i.title})
#             comment_user_fans = comment_user.fans.all()
#             # 获取评论者的fans
#             comment_fans = []
#             for f in comment_user_fans:
#                 comment_fans.append(f.id)
#             comment_user_data = {'id': comment_user.id,
#                                  'username': comment_user.username,
#                                  'avatar': comment_user.avatar,
#                                  'articles': comment_articles,
#                                  'fans': comment_fans}
#             comment_subs = Comment.objects.filter(parent_id=comment.id)
#             # 获取子评论
#             sub_data = []
#             for sub in comment_subs:
#                 subs_user = User.objects.get(id=sub.user_id)
#                 # 获取子评论用户
#                 subs_user_articles = Article.objects.filter(user_id=subs_user.id)
#                 # 获取评论者的所有文章
#                 subs_articles = []
#                 for subs_user_article in subs_user_articles:
#                     articles.append({'id': subs_user_article.id,
#                                      'title': subs_user_article.title})
#                 subs_user_fans = subs_user.fans.all()
#                 # 获取用户粉丝
#                 fans = []
#                 for k in subs_user_fans:
#                     fans.append(k.id)
#                 subs_user_data = {'id': subs_user.id,
#                                   'username': subs_user.username,
#                                   'avatar': subs_user.avatar,
#                                   'articles': subs_articles,
#                                   'fans': subs_user_fans}
#                 sub_data.append({'id': sub.id,
#                                  'content': sub.content,
#                                  'headline': id,
#                                  'user': subs_user_data,
#                                  'parent': sub.parent_id,
#                                  'subs': [],
#                                  'createtime': sub.createtime})
#             comment_data.append({'id': comment.id,
#                                  'user': comment_user_data,
#                                  'subs': sub_data,
#                                  'content': comment.content,
#                                  'createtime': comment.createtime,
#                                  'updatetime': comment.updatetime,
#                                  'parent': comment.parent_id,
#                                  'headline': id})
#
#         article_lables = article.labels.all()
#         # 获取文章标签
#         labels = []
#         for l in article_lables:
#             labels.append(l.id)
#         collecter = article.collected_users.all()
#         # 获取收藏用户
#         collected_users = []
#         for p in collecter:
#             collected_users.append(p.id)
#         return Response({'id': id,
#                          'user': user_data,
#                          'comments': comment_data,
#                          'title': article.title,
#                          'content': article.content,
#                          'image': article.image,
#                          'createtime': article.createtime,
#                          'updatetime': article.updatetime,
#                          'visits': article.visits,
#                          'thumbup': article.thumbup,
#                          'comment_count': article.comment_count,
#                          'channel': article.channel_id,
#                          'labels': labels,
#                          'collected_users': collected_users})


# 发布文章
class ArticleDetailView(RetrieveAPIView):
    serializer_class = ArticleSerializer
    queryset = Article.objects.all()
    # def get_queryset(self):
    #     id = self.kwargs.get('pk')
    #     # # 获取comment对象
    #     # comments = Comment.objects.filter(article_id=id)
    #     # for comment in comments:
    #     #     for sub in comment.subs:
    #     #         if sub.subs is None:
    #     #             break
    #     return Article.objects.filter(id=id)


    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


    # def retrieve(self, request, *args, **kwargs):
    #     instance = self.get_object()
    #     serializer = self.get_serializer(instance)
    #
    #     # 渲染数据
    #     data_dict = serializer.data
    #     image_url = data_dict['image']


class ArticleEditorView(APIView):
    """发布文章"""

    def post(self, request):
        # 接收参数
        json_data = request.body.decode()
        data = json.loads(json_data)
        content = data.get('content')
        labels = data.get('labels')
        title = data.get('title')
        image = data.get('image')
        channel_id = int(data.get('channel'))
        user = request.user
        # 获取用户对象
        try:
            # 保存数据（多对多除外）
            article = Article(content=content,
                              title=title,
                              image=image,
                              channel_id=channel_id,
                              user_id=user.id)
            article.save()
            # b保存labels
            for label in labels:
                article.labels.add(label)

            return Response({'articleid': article.id,
                             'message': '发布成功',
                             'success': True})

        except Exception as e:
            # print(e)
            return Response({'message': '发布失败',
                             'success': False})


# 发表评论
class ArticleCommentView(APIView):
    """发表评论"""

    def post(self, request, id):
        # 接收参数
        json_data = request.body.decode()
        data = json.loads(json_data)
        article_id = data.get('article')
        content = data.get('content')
        parent_id = data.get('parent')
        # 获取用户对象
        user = request.user
        # 获取文章对象
        article = Article.objects.get(id=id)
        try:
            # 保存数据至数据库

            comment = Comment(article_id=article_id,
                              content=content,
                              user_id=user.id,
                              parent_id=parent_id)
            comment.save()
            comment_count = article.comment_count
            comment_count += 1
            article.comment_count = comment_count
            article.save()
            return Response({'message': '评论成功',
                             'success': True})
        except Exception as e:
            print(e)
            return Response({'message': '评论失败',
                             'success': False})


# 搜索文章
class ArticleSearchView(ListAPIView):
    serializer_class = ArticleSerializer
    pagination_class = PageNum

    def get_queryset(self):
        # 获取前端传递的keyword值
        keyword = self.request.query_params.get('text')
        # 如果keyword是空字符，则说明要获取所有用户数据
        if keyword is '' or keyword is None:
            return Response({'message': '请输入关键字'})
        else:

            return Article.objects.filter(Q(title__contains=keyword) | Q(content__contains=keyword))
# class ArticleSearchView(SearchView):
#     """重写SearchView类"""
#
#     def create_response(self):
#         page = self.request.GET.get('page')
#         # 获取搜索结果
#         context = self.get_context()
#         print(context)
#         data_list = []
#         for article in context['page'].object_list:
#             data_list.append({
#                 'id': article.object.id,
#                 'title': article.object.title,
#                 'content': article.object.content,
#                 'createtime': article.object.createtime,
#                 'searchkey': context.get('query'),
#                 'page_size': context['page'].paginator.num_pages,
#                 'count': context['page'].paginator.count
#             })
#         # 拼接参数, 返回
#         return JsonResponse(data_list, safe=False)
